<template>
  <div class="recipe">
    <el-form ref="formRef" :model="form" :inline="true" class="top">
      <el-form-item label="设备编号:" prop="deviceCode">
        <el-select v-model="form.deviceCode" clearable placeholder="设备编号">
          <el-option
            v-for="item of deviceList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="配方名称">
        <el-input v-model="form.RecipeName" placeholder="配方名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="success" @click="addForm" v-permission="['recipe:add']"
          >新增</el-button
        >
        <el-button type="primary" @click="query" v-permission="['recipe:add']">
          <a href="/recipeTemplate.xls" download="配方模板.xls" class="a-down"
            >获取导入模板</a
          >
        </el-button>
      </el-form-item>
    </el-form>
    <div class="center" v-loading="loading">
      <sideBox class="p-t" boxTitle="已通过配方">
        <recipeTable
          ref="passRef"
          type="pass"
          :tableData="passData"
          :tableColumn="passColumn"
          @actionComman="actionComman"
          @rowClick="rowClick"
        />
      </sideBox>
      <sideBox class="p-3d">
        <template v-if="!currentRow">
          <div class="no-data">未选中已通过配方</div>
        </template>
        <template v-else>
          <div class="toggle">
            <div
              v-for="item of tdTypeArr"
              :key="item.id"
              :class="['item', tdType == item.id ? 'active' : '']"
              @click="toggleEdit(item.id)"
            >
              {{ item.label }}
            </div>
          </div>
          <div class="td-con">
            <reel3d v-if="tdType == 'reel'" from="home" :storeJson="tdJson" />
            <package3d
              v-else-if="tdType == 'package'"
              from="home"
              :storeJson="tdJson"
            />
            <innerBox3d
              v-else-if="tdType == 'innerBox'"
              :storeJson="tdJson"
              from="home"
            />
          </div>
        </template>
      </sideBox>
      <sideBox class="p-t" boxTitle="待审核配方">
        <recipeTable
          type="examine"
          :tableData="examData"
          :tableColumn="examColumn"
          @actionComman="actionComman"
        />
      </sideBox>
    </div>
    <sideBox class="bottom">
      <div v-if="!currentRow" class="no-data">暂无审核通过配方</div>
      <detailInfo from="home" :storeJson="tdJson" v-else />
    </sideBox>
  </div>
  <check :checkOpt="checkOpt" @closeDraw="closeDraw" />
</template>
<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import recipeTable from "./component/recipeTable.vue";
import sideBox from "./component/side-box.vue";
import { getRecipe, createRecipe, deleteRecipe, getDevice } from "@/api/recipe";
import { useRouter, useRoute } from "vue-router";
import editStore from "@/store/editStore";
import { useI18n } from "vue-i18n";
import reel3d from "../editFormula/preview-3d/components/reel-3d.vue";
import package3d from "../editFormula/preview-3d/components/package-3d.vue";
import innerBox3d from "../editFormula/preview-3d/components/innerBox-3d.vue";
import detailInfo from "../editFormula/preview-pdf/index.vue";
import check from "./component/check.vue";

const router = useRouter();
let store = editStore();
let { t } = useI18n();
let passColumn = [
  { prop: "deviceCode", label: "设备编号", align: "center" },
  { prop: "recipeName", label: "配方名称", align: "center" },
  { prop: "version", label: "版本号", align: "center", width: "100" },
  {
    fixed: "right",
    width: "120",
    label: "操作",
    align: "center",
    buttons: [
      {
        name: "编辑",
        type: "warning",
        command: "edit",
        permission: ["recipe:edit"],
      },
      {
        name: "删除",
        type: "danger",
        command: "delete",
        permission: ["recipe:delete"],
      },
      {
        name: "复制",
        type: "primary",
        command: "copy",
        permission: ["recipe:add"],
      },
    ],
  },
];
let examColumn = [
  { prop: "deviceCode", label: "设备编号", align: "center" },
  { prop: "recipeName", label: "配方名称", align: "center" },
  { prop: "version", label: "版本号", align: "center", width: "100" },
  {
    fixed: "right",
    width: "120",
    label: "操作",
    align: "center",
    buttons: [
      {
        name: "审核",
        type: "success",
        command: "examine",
        permission: ["recipe:check"],
      },
      {
        name: "编辑",
        type: "warning",
        command: "edit",
        permission: ["recipe:delete"],
      },
      {
        name: "删除",
        type: "danger",
        command: "delete",
        permission: ["recipe:delete"],
      },
      {
        name: "复制",
        type: "primary",
        command: "copy",
        permission: ["recipe:add"],
      },
    ],
  },
];
let form = reactive({
  deviceCode: "",
  RecipeName: "",
});

let passData = ref([]);

let examData = ref([]);

let loading = ref(false);
let passRef = ref(null);
let currentRow = ref(null);
let tdType = ref("reel");
let deviceList = ref([]);
let checkOpt = reactive({
  show: false,
  title: "",
  data: [],
});

let storeJson = ref();

let tdJson = computed(() => {
  if (currentRow.value) {
    let json = JSON.parse(currentRow.value.jsTempStr);
    json.recipe.version = currentRow.value.version;
    json.recipe.recipeNo = currentRow.value.recipeNo;
    return json;
  }
  return {};
});

let tdTypeArr = [
  { id: "reel", label: t("editFormula.reel") },
  { id: "package", label: t("editFormula.packageBag") },
  { id: "innerBox", label: t("editFormula.innerBox") },
];

async function getDeviceList() {
  try {
    deviceList.value = [];
    let res = await getDevice();
    res?.items.forEach((item) => {
      deviceList.value.push({ label: item.deviceName, value: item.deviceCode });
    });
  } catch (e) {
    ElMessage.error("获取设备信息出错");
  }
}

async function query() {
  try {
    passData.value = [];
    examData.value = [];
    loading.value = true;
    let res = await getRecipe(form);
    res.items.forEach((item) => {
      if (item.auditResults) {
        passData.value.push(item);
      } else {
        examData.value.push(item);
      }
    });
    if (passData.value.length > 0) {
      passRef.value?.tableRef?.element?.setCurrentRow(passData.value[0]);
      currentRow.value = passData.value[0];
      storeJson.value = JSON.parse(passData.value[0].jsTempStr);
      storeJson.value.recipe.version = passData.value[0].version;
      storeJson.value.recipe.recipeNo = passData.value[0].recipeNo;
    } else {
      currentRow.value = null;
      storeJson.value = null;
    }
  } catch (e) {
    console.error("获取配方出错");
  }
  loading.value = false;
}
async function addForm() {
  store.$reset();
  router.push({
    path: "/edit/formula",
    query: { type: "add" },
  });
}
function handlerEdit(row) {
  //同步后端自动添加的版本号和配方编号
  store.$state = JSON.parse(row.jsTempStr);
  store.id = row.id;
  store.recipe.recipeNo = row.recipeNo;
  store.recipe.version = row.version;
  router.push({
    path: "/edit/formula",
    query: { type: "edit" },
  });
}
function handleDel(row) {
  ElMessageBox.confirm(`是否确认删除该数据?`, "提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(async () => {
      let res = await deleteRecipe([row.id]);
      if (res) {
        ElMessage.success("删除成功");
        query();
      }
    })
    .catch(() => {
      return false;
    });
}
function handleExamine(row) {
  checkOpt.show = true;
  checkOpt.data = row;
  checkOpt.title = row.recipeName + "--" + row.version + "审核";
}
function handleCopy(row) {
  sessionStorage.setItem("copyData", row.jsTempStr);
}

function actionComman(data) {
  switch (data.command) {
    case "edit":
      handlerEdit(data.row);
      break;
    case "delete":
      handleDel(data.row);
      break;
    case "examine":
      handleExamine(data.row);
      break;
    case "copy":
      handleCopy(data.row);
      break;
    default:
      break;
  }
}
function rowClick(data) {
  currentRow.value = data.row;
}

function toggleEdit(type) {
  tdType.value = type;
}

function closeDraw(val) {
  checkOpt.show = false;
  val && query();
}

onMounted(() => {
  getDeviceList();
  query();
});
</script>
<style lang="scss">
.recipe {
  height: 100%;
  padding: 5px;
  .top {
    height: 40px;
    margin-bottom: 5px;
    .a-down {
      text-decoration: none;
      color: #fff;
    }
  }
  .center {
    height: 60%;
    display: flex;
    .p-t {
      width: 32%;
    }
    .p-3d {
      width: 36%;
      margin: 0 10px;
      .no-data {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        color: #bbb;
      }
      .toggle {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 10px;
        background-color: rgb(238 238 238 / 30%);
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        font-size: 16px;
        padding: 0 10px;
        max-width: 260px;
        margin: 0 auto;
        .item {
          width: 80px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          padding: 0 10px;
          cursor: pointer;
          color: #bbb;
        }
        .active {
          color: #0084fe;
          background-color: #d3eafe;
          border-radius: 4px;
        }
      }
      .td-con {
        height: calc(100% - 36px);
      }
    }
  }
  .bottom {
    margin-top: 10px;
    height: calc(40% - 55px);
    .no-data {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22px;
      color: #bbb;
    }
  }
}
</style>
